<template>
  <section v-if="isShow" class="dialog-wrap">

    <p class="pdv-10"></p>
    <p class="pdv-10"></p>
    <p class="pdv-10"></p>
    <p class="pdv-10"></p>
    <p class="pdv-10"></p>


    <section class="dialog-wrap-content no-shadow bg-default d-scroll-2head" >
      <div class="water-logo" v-if="list.length < 1">
        <img src="../../../static/images/dangjian/home/water-logo-comment.png" alt="">
      </div>
      <cube-scroll
        ref="scroll"
        :options="options"
        @pulling-up="onPullingUp"
      >
        <div class="block live-msg-wrap relative" v-for="(item,index) in list" :key="index">
          <!--          <span v-if="isMyComment(item)" class="color-tip delete-text" @click="deleteComment(item)">删除</span>-->
          <div class="user-avatar">
            <div class="avatar">
              <!--<img src="../../../../static/images/slidepic.jpg" alt="">-->
              <img :src="tools.getAvatarUrl(item.commentUserId)" alt="">
            </div>
            <div class="head-my">
              <div class="info">
                <h1>{{item.commentUser}} 说：</h1>
              </div>
              <div v-if="isMyComment(item.commentUserId)" class="right" @click="deleteComment(item,index)">删除</div>
            </div>
          </div>
          <div class="live-msg">{{item.commentContent}}</div>
          <div class="card-foot">
            <p class="text">{{tools.getTimeNew(item.commentTime)}}</p>
            <div class="right">
              <div class="support"><ups :key="item.commentId" v-if="item.ups !== false" :contentId="contentId" :isUp="item.isUp" :shareType="type" :commentId="item.commentId" @updateUpsAdd="updateUpsAdd(item)" :upsCount="item.ups"></ups></div>
              <div class="support" @click.stop="onfocus(item,index)"><i v-if="allowComment"  class="icon-comment"></i>{{ item.commentTotal}}
              </div>
            </div>
            <input type="hidden" v-model="flag" />
          </div>
          <div v-if="item.child && item.child.length>0" class="split-my" @click="delChildComment(item,index)"><div class="split-inner"></div><div class="middle">收起</div><i class="icon-triangle-up"></i></div>
          <div v-else-if="item.commentTotal>0" class="split-my" @click="ChildComment(item,index)"><div class="split-inner"></div><div class="middle">展开{{ item.commentTotal }}条回复</div><i class="icon-triangle-down"></i></div>
          <!--            评论别人的心得的评论-->
          <div class="recomment-my-j" v-if="item.child" v-for="(child,indexChild) in item.child" :key="index+child.commentId">
            <input type="hidden" v-model="flag" />
            <div class="head-my title">
              <!--                <div>{{ child.createUserName }}{{ getMyself(child.createUser) }}<span-->
              <div>{{ child.userName }}<span
                class="arrow_left"></span>{{ child.replyToUser }}
              </div>
              <div v-if="isMyComment(child.userId)" @click.stop="del(child.commentId,indexChild,item)" class="right-one">删除
              </div>
            </div>
            <div class="span-my" v-html="tools.resumeEnter(child.content)">
            </div>
            <div class="text">
              <div>{{ tools.getTimeNew(child.commentTime) }}</div>
              <div class="right-my">
                <div class="support">
                  <upsTwo :commentId="child.commentId" @updateUpsAdd="updateUpsAdd(child)" :upsCount="child.ups"></upsTwo>
                </div>
                <div class="support" @click="onfocusOne(child,item.commentId,index)"><i class="icon-comment"></i></div>
              </div>
            </div>
          </div>
        </div>
        <div v-if="!hasMoreList()" class="no-message">已显示全部观点</div>
        <p class="pdv-9"></p>
        <p class="pdv-9"></p>
      </cube-scroll>
    </section>

    <!--留言寄语-->
    <!-- <section class="foot-action">
       <div class="inner">
         <div class="full">
           &lt;!&ndash;<textarea :autoExpand="false" placeholder="说点什么" v-model="content"> </textarea>&ndash;&gt;
           <input placeholder="说点什么" type="text" v-model="content">
         </div>
         <div class="btn btn-small" @click="save()">
           <div class="default-block-btn">评论</div>
         </div>
       </div>
     </section>-->
    <liveMsgComponent ref="liveMsg" @newsSave="newsSave" @message="onLiveMessage" :allowShare="allowShare" :allowUp="allowUp" :allowCollection="allowCollection" v-if="preData.id" :detail="preData" :contentId="preData.id" :comments="preData.comments" :shareType="type" :commentList="true" @onComment="onComment"></liveMsgComponent>

    <div @click="back" class="bg"></div>
  </section>
</template>

<script>
import { Textarea } from 'cube-ui'
import ups from '@/components/common/upsComponent'
import upsTwo from '@/components/common/upsTwoComponent'
import liveMsgComponent from '@/components/common/liveMsgComponent'
let myInfo = {}
export default {
  name: 'commentComponent',
  props: ['_contentId', 'type','allowUp','allowCollection','allowShare'],
  components: {Textarea, ups,upsTwo, liveMsgComponent},
  data () {
    return {
      isShow: true,
      contentId: '',
      tabIndex: 0,
      pageIndex: 1,
      pageSize: 10,
      content: '',
      preData: {},
      options: {
        pullUpLoad: true,
        scrollbar: false
      },
      detail: {},
      list: [],
      flag:0,//用于刷新组件
      placeholder:'',
      replyToUser:'',//被回复人姓名
      replyToUserId:'',//被回复人id
      selectListIndex:0,//用于定位添加的列表索引
      onfocusStatus:0, //判断评论走谁的方法 0 默认 1 一级评论 2 二级评论
      isSubmiting:true,//防止重复提交 true 允许提交 false 不允许提交
      allowComment:true,//允许二级评论
      allowDel:true,//允许删除
    }
  },
  created () {
    this.preData = this.$store.state.newsDetail
    console.log('this.preData',this.preData)
    this.getList()
    myInfo = this.tools.getUserInfo()
  },
  beforeDestroy () {
    this.tools.dialogDestroy()
  },
  watch: {
    _contentId (val, oldVal) {
      this.preData = this.$store.state.newsDetail
      this.firstPage()
    }
  },
  methods: {
    updateUpsAdd(item){///用于给子组件增加点赞数
      item.ups++
      this.flag++
    },
    /*isMyComment(item) {
      return item.commentUserId === myInfo.id
    },
    /!*删除评论*!/
    deleteComment (item, index) {
      let me = this
      this.$createDialog({
        type: 'confirm',
        icon: '',
        title: '温馨提示',
        content: '确定删除？',
        confirmBtn: {
          text: '确定',
          active: true,
          disabled: false,
          href: 'javascript:;'
        },
        cancelBtn: {
          text: '取消',
          active: false,
          disabled: false,
          href: 'javascript:;'
        },
        onConfirm: () => {
          console.log('deleteComment', item)
          me.fetchService.commentDeleteMultiple({ids: [item.commentId]}).then(res => {
            if (res.code === 0) {
              this.tools.tip('删除成功')
              this.$store.state.newsDetail.comments--
              me.list.splice(index, 1)
              this.$refs.liveMsg.commentDeduce()
            }
          })
        }
      }).show()
    },*/
    onfocus(item,index) { //一级评论的的回复
      console.log('onfocusNew',item);
      if(typeof item !== 'undefined'){
        this.placeholder = '回复'+item.commentUser+':'
        this.selectListIndex = index
        this.commentNewId = item.commentId
        this.replyToUser = item.commentUser
        this.replyToUserId = item.commentUserId
        this.onfocusStatus = 1
      }
      this.$refs.liveMsg.focusChild(this.placeholder);
      // this.textareaClass = 'on-focus'
    },
    onfocusOne(child,id,index){//二级评论
      console.log('onfocusOne',child);
      if(typeof child !== 'undefined'){
        this.placeholder = '回复'+child.userName+':'
        this.selectListIndex = index
        this.commentNewId = id
        this.replyToUser = child.userName
        this.replyToUserId = child.userId
        this.onfocusStatus = 2
      }
      this.$refs.liveMsg.focusChild(this.placeholder);
    },
    ChildComment(item, index) { //查询二级评论
      if(typeof this.shareType !='undefined' && this.shareType ===7){ //组工信息的二级评论查看
        let dataNew = {
          contentId:this.contentId,
          pageNo: 1,
          pageSize: 1000,
          commentId: item.commentId,
        }
        this.fetchService.groupInfoCommentInfoPage(dataNew).then(res => {
          if (res.code !== 0) {
            return this.tools.tip(res.message)
          }
          this.list[index].child = this.getGroupInfoDateTwo(res.data)
          this.flag++
        })
        return
      }
      let dataNew = {//新闻的二级评论
        contentId:this.contentId,
        pageNo: 1,
        pageSize: 1000,
        commentId: item.commentId,
      }
      this.fetchService.commentPage(dataNew).then(res => {
        if (res.code !== 0) {
          return this.tools.tip(res.message)
        }
        this.flag++
        this.getGroupInfoDateNews(index,res.data)
      })
    },
    delChildComment(item, index){ //清空二级评论
      this.flag--
      this.list[index].child = []
    },
    onComment () {

    },
    hasMoreList () {
      return !(this.list.length > 0 && this.noMore)
    },
    onLiveMessage () {
      this.preData.comments ++
      this.firstPage()
    },
    getList () {
      this.tabIndex = 0
      let id = this._contentId
      this.contentId = id
      let params = {
        contentId: id,
        pageNo: this.pageIndex + '',
        pageSize: this.pageSize + ''
      }
      return this.fetchService.commentPage(params).then(res => {
        if (res.code !== 0) {
          return this.tools.tip(res.message || '接口服务出错，请联系管理员')
        }
        if (res.data.length === 0 && this.pageIndex !== 1) {
//            this.tools.tip('已无更多数据')
          this.noMore = true
        }
        this.pageIndex++
        this.$refs.scroll.forceUpdate && this.$refs.scroll.forceUpdate()
        this.list = this.list.concat(res.data)
        return res
      })
    },
    liveMessage () {
      this.tabIndex = 1
    },
    /*新闻评论*/
    newsSave(obj,callback){
      /*let params = {
        "content": this.content,
        "contentId": this.contentId
      }*/
      let params = {
        content: obj.content,
        contentId: this.contentId,
        replyToUser: this.replyToUser,
        replyToUserId: this.replyToUserId,
        supCommentId: this.commentNewId
      }
      this.tools.showLoading()
      this.fetchService.commentAdd(params).then(res => {
        this.tools.hideLoading()
        callback(res.code);//把返回值传给子组件
        if (res.code === 0) {
          // let data = this.getGroupInfoDate(res.data)
          let data = res.data
          data.commentUserId = data.userId
          if(this.onfocusStatus === 0){ //判断评论走谁的方法 0 默认
            data.commentContent = data.content
            this.list.unshift(data)
            this.$refs.liveMsg.commentAdd()
            this.$store.state.newsDetail.comments++
            this.flag ++
          }else if(this.onfocusStatus === 1){//判断评论走谁的方法 1 一级评论
            this.list[this.selectListIndex].commentTotal++
            if(this.list[this.selectListIndex].child && this.list[this.selectListIndex].child.length>0){
              this.list[this.selectListIndex].child.push(this.getNewsInfoDate(data))
            }
            this.flag ++
          }else if(this.onfocusStatus === 2){ //判断评论走谁的方法 2 二级评论
            this.list[this.selectListIndex].commentTotal++
            this.list[this.selectListIndex].child.push(this.getNewsInfoDate(data))
            this.flag ++
          }
          this.clearContent()
        }
        return this.tools.tip(res.message || '接口服务出错，请联系管理员', 2000)
      })
    },
    clearContent(){//清空数据
      this.content = ''
      this.isSubmiting = true
      this.commentNewId = '' //清空commentNewId 防止前一个数据带过来
      this.replyToUser = '' //清空replyToUser
      this.replyToUserId = '' //清空replyToUserId
      this.onfocusStatus = 0
      // this.$refs.liveMsg.blur();//提交完成以后失去焦点
      return this.tools.tip('评论成功', 2000)
    },
    getGroupInfoDateNews(index,data){ // 新闻评论二级数据的处理 - 列表
      data.forEach( (item,index)=>{
        data[index].content = item.commentContent
        data[index].userName = item.commentUser
        data[index].userId = item.commentUserId
        data[index].isUp = false
        /*this.hashUp(item.commentId).then(res=>{
          console.log('resss===',res);
          data[index].isUp = res
       })*/
      })
      this.list[index].child = data
    },
    getNewsInfoDate(data){ // 新闻评论二级数据的处理
      data.userName = data.commentUser
      data.userId = data.commentUserId
      data.isUp = false
      return data
    },
    upComment(item) {
      if (item.isUp == true) {
        return false
      }
      let params = {
        commentId: item.commentId,
        type: 1,
        contentId: this.contentId,
      }
      if(typeof this.shareType !='undefined' && this.shareType ===7){ //组工信息的评论点赞
        this.fetchService.groupInfoCommentInfoUps(params).then(res => {
          if (res.code !== 0) {
            return this.tools.tip(res.message || '接口服务出错，请联系管理员')
          }
          this.flag --
          item.isUp = true
          item.ups ++
          return res
        })
        return
      }
      return this.fetchService.upsAndDowns(params).then(res => {//新闻适配点赞
        if (res.code !== 0) {
          return this.tools.tip(res.message || '接口服务出错，请联系管理员')
        }
        this.flag --
        item.isUp = true
        item.ups ++
        return res
      })
    },
    isMyComment(userId) {
      return userId === myInfo.id
    },
    //删除二级评论
    del(id, index,list) {
      let _this = this
      this.$createDialog({
        type: 'confirm',
        title: "温馨提示",
        content: '确认删除？',
        confirmBtn: {
          text: '确定',
          active: true,
          disabled: false,
          href: 'javascript:;'
        },
        cancelBtn: {
          text: '取消',
          active: false,
          disabled: false,
          href: 'javascript:;'
        },
        onConfirm: () => {
          if (_this.shareType === 7) {  //类型为组工信息
            return _this.deleteMaterial(id, index,list);
          }
          _this.fetchService.commentDeleteCommentByNews(id,this._contentId).then(res => {
            if (res.code === 0) {
              this.tools.tip("删除成功")
              list.child.splice(index, 1)
              list.commentTotal--
            }
          })
        },
        onCancel: () => {
        }
      }).show()
    },
    deleteMaterial(id, index,list) {
      this.fetchService.groupInfoCommentInfoDelete(id).then(res => {
        if (res.code !== 0) {
          return this.tools.tip(res.message)
        }
        this.tools.tip("删除成功")
        list.child.splice(index, 1)
        list.commentTotal--
      })
    },
    /*删除评论*/
    deleteComment (item, index) {
      let me = this
      this.$createDialog({
        type: 'confirm',
        icon: '',
        title: '温馨提示',
        content: '确定删除？',
        confirmBtn: {
          text: '确定',
          active: true,
          disabled: false,
          href: 'javascript:;'
        },
        cancelBtn: {
          text: '取消',
          active: false,
          disabled: false,
          href: 'javascript:;'
        },
        onConfirm: () => {
          if (me.shareType === 7) {
            return me.groupInfoCommentInfoDelete(item.commentId, index)
          }
          me.fetchService.commentDeleteCommentByNews(item.commentId,this._contentId).then(res => {
            if (res.code === 0) {
              this.tools.tip('删除成功')
              this.$store.state.newsDetail.comments--
              me.list.splice(index, 1)
              this.$refs.liveMsg.commentDeduce()
            }
          })
        }
      }).show()
    },
    /*save (obj,callback) {
      debugger
      /!*if (this.content.length == 0 || this.content.trim().length == 0) {
        return this.tools.alert('请填写留言')
      }*!/
      let params = {
        "content":  obj.content,
        "contentId": this.preData.id
      }
      this.tools.showLoading()
      this.fetchService.commentAdd(params).then(res => {
        this.tools.hideLoading()
        if (res.code === 0) {
          callback(res.code);//把返回值传给子组件
          this.firstPage()
          this.$store.state.newsDetail.comments++
          return this.tools.alert('评论成功')
        }
      })
    },*/
    firstPage () {
      this.list = []
      this.pageIndex = 1
      this.getList()
    },
    onPullingUp () {
      this.getList().then(res => {
        setTimeout(() => {
          this.$refs.scroll.forceUpdate && this.$refs.scroll.forceUpdate(true, false)
          this.options.isPullUpLoad = !true
        }, 100)
      })
    },
    show () {
      this.isShow = true
      this.tools.dialog(1, this)
      return this
    },
    back () {
      this.tools.dialog(-1)
      this.isShow = false
    }
  }
}
</script>

<style scoped lang="scss">
@import "@/common/stylus/moon.scss";
.dialog-wrap {
  position: fixed;
  top: 0; right: 0; left: 0; bottom: 0; z-index: 99;
  background:none;
  .dialog-wrap-content {
    position: relative;
    z-index: 2;
    border-radius:20px 20px 0 0;
    overflow: hidden;
  }
  .bg {
    position: absolute;
    z-index: 1;
    top: 0; right: 0; left: 0; bottom: 0;
    @include fullImg();
    background: rgba(0, 0, 0, .2);
    opacity: 0.5;
  }
}
.cube-textarea-wrapper {
  textarea {
    height: auto;
  }
}
.live-msg-wrap .user-avatar .info h1 {
  font-size: 15PX;
}
</style>
